package logic

import (
	"context"
	"errors"
	"goods_srv/cache"
	"goods_srv/pkg"
	"math/rand"
	"strconv"
	"time"

	"goods_srv/goods"
	"goods_srv/internal/svc"

	"github.com/zeromicro/go-zero/core/logx"
)

type SendSmsLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewSendSmsLogic(ctx context.Context, svcCtx *svc.ServiceContext) *SendSmsLogic {
	return &SendSmsLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

// 短信发送请求
func (l *SendSmsLogic) SendSms(in *goods.SendSmsRequest) (*goods.SendSmsResponse, error) {
	// todo: add your logic here and delete this line

	//记录短信发送次数
	count := cache.Rdb.Get(l.ctx, "sendSmsErr"+in.Mobile).Val()
	if count == "1" {
		logx.Error("当前短信只允许5分钟发送一次")
		return nil, errors.New("当前短信只允许5分钟发送一次")
	}

	//随机生成4位
	code := rand.Intn(9000) + 1000

	//调用封装函数
	sms, err := pkg.SendSms(in.Mobile, strconv.Itoa(code))
	if err != nil {
		logx.Error("短信发送失败")
		return nil, errors.New("短信发送失败")
	}

	//判断手机号
	if *sms.Body.Code != "OK" {
		logx.Error()
		return nil, errors.New(*sms.Body.Message)
	}

	//缓存
	cache.Rdb.Set(l.ctx, "sendSms"+in.Mobile, code, time.Minute*30)

	//记录发送次数 发送次数自增
	cache.Rdb.Incr(l.ctx, "sendSmsErr"+in.Mobile)
	//限制发送时间
	cache.Rdb.Expire(l.ctx, "sendSmsErr"+in.Mobile, time.Minute*5)

	return &goods.SendSmsResponse{}, nil
}
